package com.dy.org.service.impl;

import com.dy.basic.query.BaseQuery;
import com.dy.basic.service.impl.BaseServiceImpl;
import com.dy.basic.util.PageList;
import com.dy.org.domain.Employee;
import com.dy.org.mapper.EmployeeMapper;
import com.dy.org.service.EmployeeService;
import com.dy.org.vo.EmpAndRoleVo;
import com.dy.system.mapper.RoleMapper;
import com.dy.user.mapper.LogininfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 添加emp表和中间表的信息
     * @param employee
     */
    @Override
    @Transactional
    public void add(Employee employee) {
        employeeMapper.add(employee);
        roleMapper.addEmpRole(employee.getId(),employee.getRoles());
    }


    /**
     * 修改用户的信息
     */
    @Override
    @Transactional
    public void update(Employee employee) {
        // 修改用户的信息的话先删除中间表的信息在进行数据的添加
        // 删除中间表的数据
        roleMapper.deleteRoleEmp(employee.getId());
        // 删除后在添加中间表的信息
        roleMapper.addEmpRole(employee.getId(), employee.getRoles());

        employeeMapper.update(employee);
    }

    /**
     * 删除emp表和中间表(emp_role)的数据
     * @param id
     */
    @Override
    @Transactional
    public void delete(Long id) {
        roleMapper.deleteRoleEmp(id);
        employeeMapper.delete(id);
    }

    // 分页
    @Override
    public PageList<Employee> queryByPage(BaseQuery query) {
        PageList<Employee> pageList = super.queryByPage(query);
        if (null == pageList || CollectionUtils.isEmpty(pageList.getRows())){
            return pageList;
        }
        // 得到分页查询的数据
        List<Employee> emps = pageList.getRows();
        // 把empIds的id存到一个集合中
        List<Long> empIds = emps.stream().map(Employee::getId).collect(Collectors.toList());
        // 根据集合的id去查询数据
        List<EmpAndRoleVo> empAndRoleVos = roleMapper.findByEmpIds(empIds);
        //
        Map<Long, List<Long>> map = empAndRoleVos.stream().collect(Collectors.groupingBy(EmpAndRoleVo::getEmployeeId
                , Collectors.mapping(EmpAndRoleVo::getRoleId, Collectors.toList())));

        emps.forEach(employee -> {
            List<Long> rolesIds = map.get(employee.getId());
            employee.setRoles(rolesIds);
        });
        return pageList;
    }



}
